/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package game.source.sound;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class WavePlayer extends Thread{

	private SourceDataLine sound;
	private AudioBuffer buffer;
	private boolean pause;
	private boolean	end;

	public WavePlayer(String path){
		this(new AudioBuffer(path));
	}

	public WavePlayer(AudioBuffer buffer){
		try{
			this.buffer = buffer;
			this.sound = AudioSystem.getSourceDataLine(buffer.getFormat());
			try {
				this.sound.open(buffer.getFormat(),buffer.getLength());	
			} catch (LineUnavailableException e){
				e.printStackTrace();
			}
			this.pause	= true;
			this.end	= false;
			this.start();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void play(){
		this.pause = false;
		this.notify();
	}

	public synchronized void end(){
		this.sound.close();
		this.end = true;
		this.pause = false;
		this.notify();
	}

	@Override
	public void run(){
		while(!this.end){
			synchronized (this) {
				while(this.pause){
					try {
						this.wait();
					} catch(InterruptedException e){
						e.printStackTrace();
					}
				}	
			}
			this.sound.start();
			this.sound.write(buffer.getSound(), 0, buffer.getLength());
			this.pause = true;
		}
	}
}